<template>
  <view class="page">
    <!-- #ifndef MP-WEIXIN-->
    <my-navbar leftText="退货单" @leftClick="back"></my-navbar>
    <!-- #endif -->
    <view class="goods_box">
      <view class="food-box">
        <view class="pics" style="margin-top: 20rpx">
          <view class="fonts_26">退货原因：</view>
          <u-input
            v-model="return_remark"
            placeholder="请选择退货原因"
            border-color="#cccccc"
            :type="type"
            :border="border"
            @click="show = true"
          />
          <u-action-sheet
            :list="choselist"
            v-model="show"
            @click="SheetCallback"
          >
          </u-action-sheet>
          <view
            class="del-btn"
            style="margin-left: 10px; margin-top: 5px"
            @click="removeAll"
            >批量删除</view
          >
        </view>
        <view v-if="index == 4" class="sales">
          <input
            type="text"
            placeholder="请输入退货原因"
            v-model="sales"
            class="sales-input"
          />
        </view>
        <view class="shops-box" v-for="(item, index) in goodsList" :key="index">
          <view class="pics">
            <image class="picture" :src="item.img" mode="widthFix"></image>
            <view class="header-flex lf-m-l15">
              <view class="fonts_26">{{ item.name }}</view>
              <view class="spu">{{ item.unit }}</view>
            </view>
            <view class="del-btn" @click="scdelete(index)">删除</view>
          </view>

          <view class="flex1">
            <view class="flex">
              <view>配送数量：{{ item.sort_num }}</view>
              <text class="lf-m-l15"
                >配送单价：￥{{ Number(item.sort_price).toFixed(2) }}</text
              >
              <text class="lf-m-l15"
                >配送金额：￥{{ Number(item.sort_money).toFixed(2) }}</text
              >
            </view>
            <view class="flex">
              <text>退货单价：￥{{ Number(item.apply_price).toFixed(2) }}</text>
              <view class="lf-m-l15"
                >已退数量：{{ Number(item.return_num).toFixed(2) }}</view
              >
              <text class="lf-m-l15"
                >退货金额：￥{{ Number(item.apply_money).toFixed(2) }}</text
              >
            </view>
          </view>

          <view class="add-box">
            <image
              class="add"
              @click="addgoods(1, index, item)"
              src="/static/image/sub.svg"
            ></image>
            <view
              class="add-txt"
              v-show="!item.showinput"
              @click="addnum(item)"
            >
              {{ item.apply_num }}
            </view>
            <input
              v-show="item.showinput"
              class="border"
              type="digit"
              :class="[item.return_status >= 2 ? 'dis' : 'border']"
              @input="onKeyInput($event, item)"
              @blur="onKeyInputBlur(item)"
              :disabled="item.return_status >= 2 ? true : false"
              v-model="item.apply_num"
            />
            <image
              class="add"
              @click="addgoods(2, index, item)"
              src="/static/image/add.svg"
            >
            </image>
          </view>
        </view>

        <view class="main_tile">
          <em></em>上传凭证
          <span>文件小于2M，最多添加5张</span>
        </view>

        <view class="slot-btn">
          <view class="pic-box">
            <view class="pic-list" v-for="(item, index) in form.pics" :key="index">
              <view @click="previewImg">
                <image class="pictures" :src="item" mode="aspectFit"></image>
              </view>

              <view class="colse" @click="del(index)">
                <u-icon name="close" color="#333333" size="35"></u-icon>
              </view>
            </view>
          </view>

          <view class="carame" v-if="form.pics.length < 5" @click="upload">
            <u-icon name="camera-fill" color="#333333" size="60"></u-icon>
          </view>
        </view>

        <view class="accountBar ft-btw">
          <view class="right">
            <view class="flex-center fonts_26"
              >合计：
              <view class="flex-column">
                <text class="price">￥{{ total }}</text>
              </view>
            </view>
            <view class="to flex-center" @click="toOrder">确认退货</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { $https } from "@/static/js/request.js";
import MixinShowprice from "@/static/js/mixinshowprice.js";
export default {
  data() {
    return {
      orderInfo: [], //订单信息
      goodsList: [], //商品列表
      form: {
        pics: [],
      },
      forms: {
        pics: [],
      },
      type: "select",
      show: false,
      border: true,
      index: "",
      sales: "",
      choselist: [
        {
          text: "菜品错送",
        },
        {
          text: "其他原因",
        },
        {
          text: "菜品损坏",
        },
        {
          text: "菜品多送",
        },
        {
          text: "菜品变质",
        },
      ],
      return_remark: "菜品错送",
    };
  },
  onLoad(option) {
    this.getData(option.id);
  },
  computed: {
    total() {
      let price = 0;
      this.goodsList.map((item) => {
        price += Number(item.apply_price) * item.apply_num;
      });
      return price.toFixed(2);
    },
  },
  watch: {
    goodsList: {
      handler(newarray, oldarray) {
        newarray.forEach((value) => {
          if (!value.apply_num) {
            value.apply_num = 0;
          }
        });
      },
      deep: true,
    },
  },
  methods: {
    //返回上一页面
    getData(id) {
      $https(
        "GET",
        "getOrderDetail",
        {
          oid: id,
        },
        (res) => {
          res.data.data.goods_info.map((e) => {
            this.$set(e, "showinput", false);
            e.apply_num = 0;
            e.apply_price = e.sort_price;
            e.apply_money = 0;
            if (e.apply_num && e.apply_price) {
              e.apply_money = this.$toFixed(
                parseFloat(e.apply_num * e.apply_price)
              );
            }
          });
          (this.goodsList = res.data.data.goods_info),
            (this.orderInfo = res.data.data.order_info);
        }
      );
    },
    back() {
      // #ifdef H5
      uni.hideKeyboard();
      window.history.back(-1);
      // #endif
      // #ifndef H5
      uni.navigateBack({
        delta: 1,
      });
      // #endif
    },
    removeAll() {
      uni.showModal({
        content: `确认批量删除退货数量为0的商品吗？`,
        confirmColor: "#40AE36",
        success: (res) => {
          if (res.confirm) {
            this.goodsList = this.goodsList.filter((e) => {
              return e.apply_num > 0;
            });
          } else if (res.cancel) {
          }
        },
      });
    },
    //退货原因选择
    SheetCallback(index) {
      this.index = index;
      this.return_remark = this.choselist[index].text;
    },
    //数量键盘输入监听
    onKeyInput(e, item) {
      console.log(e.target);
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,2})/g)[0] || null;
      //重新赋值给input
      this.$nextTick(() => {
        if (e.target.value < parseFloat(item.sort_num - item.return_num)) {
          item.apply_num = e.target.value;
          item.apply_money =
            parseFloat(item.apply_price) * parseFloat(item.apply_num);
          item.apply_money.toFixed(2);
        } else {
          e.target.value = parseFloat(item.sort_num - item.return_num);
          item.apply_num = e.target.value;
          item.apply_money =
            parseFloat(item.apply_price) * parseFloat(item.apply_num);
          item.apply_money.toFixed(2);
        }
      });
    },
    //数量输入框失去焦点
    onKeyInputBlur(item) {
      item.showinput = false;
    },
    //商品数量的添加
    addgoods(type, index, item) {
      if (type == 2) {
        if (item.return_status == 2) {
          uni.showToast({
            title: "此商品已全退完",
            icon: "none",
          });
        } else {
          if (item.apply_num >= parseFloat(item.sort_num - item.return_num)) {
            uni.showToast({
              title: "不能超过配送数量",
              icon: "none",
            });
          } else {
            item.apply_num++;
            item.apply_money =
              parseFloat(item.apply_price) * parseFloat(item.apply_num);
            item.apply_money.toFixed(2);
          }
        }
      } else {
        if (item.apply_num == 0) {
          item.apply_num = 0;
        } else {
          item.apply_num--;
          item.apply_money =
            parseFloat(item.apply_price) * parseFloat(item.apply_num);
          item.apply_money.toFixed(2);
        }
      }
    },

    //控制输入框的显示
    addnum(item) {
      if (item.return_status == 2) {
        uni.showToast({
          title: "此商品已全退完",
          icon: "none",
        });
      } else {
        item.showinput = true;
      }
    },
    //提交订单
    toOrder() {
      let arr = [];
      let newarr = [];
      let ids = this.goodsList.filter((item) => item.return_status <= 1);
      newarr = ids;
      if (newarr.length == 0) {
        uni.showToast({
          title: "此商品已全部退完或无退货商品",
          icon: "none",
        });
        return;
      }
      let flag = newarr.every((item) => !!item.apply_num);
      if (!flag) {
        uni.showToast({
          title: "退货数量不能为零",
          icon: "none",
        });
        return;
      } else {
        newarr.map((e) => {
          arr.push({
            related_id: e.id,
            apply_num: e.apply_num,
            apply_money: e.apply_money,
          });
        });
        uni.showModal({
          content: "确认申请退货",
          confirmColor: "#40AE36",
          success: (res) => {
            if (!this.sales.trim()) {
              this.sales = "其它原因";
            }
            if (res.confirm) {
              let options = {
                related_id: this.orderInfo.id,
                pics: JSON.stringify(this.forms.pics),
                return_remark:
                  this.index == 4 ? this.sales.trim() : this.return_remark,
                list: JSON.stringify(arr),
              };
              $https("POST", "addOrderReturn", options, (res) => {
                if (res.data.errcode == "-1") {
                  uni.showToast({
                    title: res.data.errmsg,
                    icon: "none",
                    success: function () {
                      setTimeout(function () {
                        uni.switchTab({
                          url: "/pages/tabar/order",
                        });
                      }, 1000); //延迟时间
                    },
                  });
                }
                if (res.data.errcode == 0) {
                  uni.switchTab({
                    url: "/pages/tabar/order",
                  });
                }
              });
            }
          },
        });
      }
    },
    //上传图片
    upload() {
      let that = this;
      let imgLength = that.form.pics.length;
      if (imgLength < 5) {
        uni.chooseImage({
          count: 5,
          sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album"], //从相册选择
          success: function (res) {
            let type = res.tempFiles[0].type;
            let typeList = ["image/jpeg", "image/jpg", "image/png"];
            let isType = false;
            typeList.forEach((e) => {
              if (e == type) {
                isType = true;
                return;
              }
            });
            const isLt2M = res.tempFiles[0].size / 1024 / 1024 < 2;
            if (!isType) {
              uni.showToast({
                title: "请上传正确的图片格式",
                icon: "none",
              });
            }

            if (!isLt2M) {
              uni.showToast({
                title: "上传头像图片大小不能超过 2MB!",
                icon: "none",
              });
            } else {
              let imgsFile = res.tempFilePaths[0];
              let uploadImgCount = 0;
              uni.showToast({
                title: "正在上传...",
                icon: "none",
              });
              uni.uploadFile({
                url: `${getApp().globalData.rootUrl}/partner/uploadFeedImg`,
                // url: `https:/test.caidj.net.cn/partner/uploadFeedImg`,
                filePath: imgsFile,
                name: "img",
                formData: {
                  type: 3,
                },
                header: {
                  Authorization: uni.getStorageSync("copartner_token"),
                },
                success(res) {
                  let data = JSON.parse(res.data);
                  that.form.pics = that.form.pics.concat(data.data.src);
                  that.forms.pics = that.forms.pics.concat(data.data.img_path);
                },
              });
            }
          },
        });
      } else {
        uni.showToast({
          title: "最多上传五张",
          icon: "none",
        });
      }
    },
    //删除对应图片
    del(index) {
      this.form.pics.splice(index, 1);
    },
    //查看图片
    previewImg() {
      let that = this;
      uni.previewImage({
        urls: that.form.pics, //提取图片数组
      });
    },
    // 删除
    scdelete(index) {
      this.goodsList.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  height: auto;

  .goods_box {
    height: auto;
    padding: 0rpx 30rpx;
  }

  .food-box {
    height: auto;
    overflow-x: auto;
    padding-bottom: 152rpx;

    .shops-box {
      background-color: white;
      margin-top: 20rpx;
      padding: 20rpx;
      border-radius: 10rpx;
    }

    .pics {
      display: flex;
      height: auto;
      flex: 1;
    }

    .sales {
      width: 100%;
      height: auto;
      display: flex;
      align-items: center;
      margin-top: 20rpx;

      .sales-input {
        width: 275px;
        height: 60rpx;
        border: 1px solid #ccc;
        border-radius: 10rpx;
        margin-left: auto;
        padding-left: 20rpx;
        box-sizing: border-box;
        font-size: 24rpx;
      }
    }

    .picture {
      width: 120rpx;
      height: 120rpx;
    }

    .header-flex {
      display: flex;
      flex: 1;
      align-items: center;
    }

    .flex1 {
      flex: 1;
    }

    .spu {
      margin-left: 20rpx;
      padding: 4rpx 8rpx;
      background: #f5f5f5;
      border-radius: 8rpx;
      font-size: 24rpx;
      transform: scale(0.8);
    }

    .del-btn {
      background-color: #e84b4b;
      height: 50rpx;
      line-height: 50rpx;
      padding: 0rpx 16rpx;
      color: white;
      border-radius: 10rpx;
      font-size: 24rpx;
    }

    .add-box {
      display: flex;
      justify-content: flex-end;
      margin: 30rpx 0rpx 20rpx 0rpx;
    }

    .add {
      width: 55rpx;
      height: 55rpx;
    }

    .border{
      margin-top: 3rpx;
    }

    .add-txt {
      padding: 7.5rpx 24rpx;
    }
  }
}

.flex {
  flex: 1;
  font-size: 26rpx;
  margin-top: 20rpx;
}

.lf-m-l15 {
  margin-left: 30rpx;
}

.border {
  width: 100rpx;
  margin: 0rpx 10rpx;
  height: 44rpx;
  text-align: center;
  border: 1px solid #cccccc;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.accountBar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 116rpx;
  padding-left: 24rpx;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  color: #737373;

  .right {
    display: flex;
    align-items: center;

    .price {
      color: #e84b4b;
      font-size: 26rpx;
    }

    .jf {
      color: #e84b4b;
      font-size: 24rpx;
    }

    .to {
      margin-left: 30rpx;
      width: 210rpx;
      height: 116rpx;
      background: $dgreen;
      color: #fff;
    }
  }
}

.ft-btw {
  display: flex;
  justify-content: space-between;
  align-items: center;
  justify-content: flex-end;
}

.slot-btn {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  flex-wrap: wrap;
}

.pic-box {
  height: auto;
  display: flex;
  align-items: center;
}

.carame {
  width: 150rpx;
  height: 150rpx;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 12rpx;
}

.colse {
  position: absolute;
  right: 10rpx;
  top: 0rpx;
}

.pic-list {
  position: relative;
  height: 150rpx;
}

.pictures {
  width: 150rpx;
  height: 150rpx;
  margin: 0rpx 18rpx 18rpx 0rpx;
}

.main_tile {
  color: #181818;
  font-size: 26rpx;
  font-weight: bold;
  padding-top: 20rpx;
}

.main_tile em {
  display: inline-block;
  vertical-align: 2px;
  border-radius: 1000px;
  margin-right: 5px;
  width: 6px;
  height: 6px;
  background: $dgreen;
}

.main_tile span {
  color: #eb0a0a;
  font-size: 24rpx;
}

.dis {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

/deep/.u-drawer-bottom {
  background-color: white;
}
</style>
